package com.itany.shop.dao.impl;

import com.itany.shop.dao.OrderDao;
import com.itany.shop.entity.Order;
import com.itany.shop.exception.DataAccessException;
import com.itany.shop.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 黄衡熙
 * @version 1.0
 */
public class OrderDaoImpl implements OrderDao {
    @Override
    public Integer insertReturnPrimaryKey(Order order) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Integer id = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_order(no,price,user_id)")
                    .append(" values(?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
            ps.setString(1, order.getNo());
            ps.setDouble(2, order.getPrice());
            ps.setInt(3, order.getUser().getId());
            ps.executeUpdate();
            // 获取返回的主键
            rs = ps.getGeneratedKeys();
            while (rs.next()) {
                id = rs.getInt(1);
            }
        } catch (SQLException e) {
            throw new DataAccessException("数据访问异常");
        }
        return id;
    }

    @Override
    public List<Order> selectByUserId(Integer userId) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Order> orders = new ArrayList<>();
        try {
            conn = JDBCUtil.getConnection();
            // 只查询id和no字段
            String sql = "select id, no , price ,user_id from t_order where user_id = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, userId);
            rs = ps.executeQuery();
            while (rs.next()) {
                Order order = new Order();
                order.setId(rs.getInt("id"));
                order.setNo(rs.getString("no"));
                order.setPrice(rs.getDouble("price"));
                orders.add(order);
            }
            return orders;
        } catch (SQLException e) {
            throw new DataAccessException("根据user_id查询订单id和no失败", e);
        }
    }
}
